package com.palmar.proxy.handler.socks;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.socksx.v5.*;

public class SocksCommandHandler extends SimpleChannelInboundHandler<Socks5CommandRequest> {
    //客户端程序用于连接 目的服务器
    private Bootstrap bootstrap;

    public SocksCommandHandler(Bootstrap bootstrap) {
        this.bootstrap = bootstrap;
    }

    @Override
    protected void messageReceived(ChannelHandlerContext ctx, Socks5CommandRequest msg) throws Exception {
        if (msg.type().equals(Socks5CommandType.CONNECT)) {
            //CONNECT 用于TCP场景
            final ChannelFuture connectFuture = this.bootstrap.connect(msg.dstAddr(), msg.dstPort());
            connectFuture.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    //更新channelPipeline 的中handler
                    //删除 Socks5InitialRequestDecoder、Socks5PasswordAuthRequestDecoder、Socks5CommandRequestDecoder
                    //分别向客户端通道，远程服务器通道 添加数据转发handler
                }
            });
        } else if (msg.type().equals(Socks5CommandType.UDP_ASSOCIATE)) {
            //UDP场景
            //获取客户端开放的UDP端口


        } else {
            //其他场景暂不支持
            ctx.writeAndFlush(new DefaultSocks5CommandResponse(Socks5CommandStatus.CONNECTION_REFUSED, msg
                    .dstAddrType())).addListener(ChannelFutureListener.CLOSE);
        }

    }
}
